/*
 * Copyright @ 2024 weili23
 * com.iflytek.zhcs.assist.portal.service.impl 15:36
 * All right reserved.
 */

package com.sky.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sky.service.IWeatherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @desc: 天气
 * @author: weili23
 * @createTime: 2024/12/16 15:36
 * @version: v1.0
 */
@Service
@Slf4j
public class WeatherServiceImpl implements IWeatherService {

    @Value("${sky.weather.url:}")
    private String weatherUrl;
    @Value("${sky.weather.appCode:}")
    private String appCode;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private static final String WEATHER_KEY=":weather:";
    @Override
    public JSONObject  getWeather(String cityName) {
        JSONObject jsonObject = null;
        try{
            //获取当前年月日
            String currentDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String redisResult = stringRedisTemplate.opsForValue().get(currentDate + WEATHER_KEY + cityName);
            if(StringUtils.isNotBlank(redisResult)){
                log.info("从redis中获取的结果");
                jsonObject = JSON.parseObject(redisResult);
                return jsonObject;
            }
            // 创建一个GET请求
            HttpRequest request = HttpUtil.createGet(weatherUrl);
            // 添加请求参数
            request.form("area", cityName);
            // 添加请求头
            request.header("Authorization", "APPCODE "+appCode);

            // 发送请求并获取响应
            String response = request.execute().body();
            if(response != null){
                log.info("从接口中获取的结果");
                //设置一天过期
                stringRedisTemplate.opsForValue().set(currentDate + WEATHER_KEY + cityName, response,1L, TimeUnit.DAYS);

            }
            jsonObject = JSON.parseObject(response);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    
    public static void main(String[] args){
        System.out.println("LocalTime.now() = " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
    }
}
